/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.media;

import com.sun.org.apache.bcel.internal.util.ClassPath;
import database.Database;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Not Stephen
 */
public class Upload extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //Check if isMultipart
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
           int tripId = Integer.parseInt(request.getParameter("tripId"));
           int eventId = (request.getParameter("eventId") == null ? -1 : Integer.parseInt(request.getParameter("eventId")));
       // int tripId = 1;
       // int eventId = -1;
        if (!isMultipart) {
            System.out.println("File Not Uploaded");

            // RETURN TO PAGE (get a parameter that gives the page sent from( I.E account or event page )
            RequestDispatcher rd = request.getRequestDispatcher("./accountpage.jsp#invalidUpload");
            rd.forward(request, response);
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
            System.out.println("items: " + items);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
            } else {
                String finalimage = "NO FINAL IMAGE";
                String loc = System.getProperty("user.dir") + "/MEDIA/";
                String root = "./MEDIA/";
                try {
                    String itemName = item.getName();
                    Random generator = new Random();
                    int r = Math.abs(generator.nextInt());

                    String reg = "[.*]";
                    String replacingtext = "";
                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(itemName);
                    StringBuffer buffer = new StringBuffer();

                    while (matcher.find()) {
                        matcher.appendReplacement(buffer, replacingtext);
                    }
                    int IndexOf = itemName.indexOf(".");
                    String domainName = itemName.substring(IndexOf);

                    finalimage = buffer.toString() + "_" + r + domainName;
                    File dir = new File(loc);
                    dir.mkdirs();
                    File savedFile = new File(loc + finalimage);
                    item.write(savedFile);

                    Connection c = Database.getConnection();
                    if (c != null) {
                        PreparedStatement s = c.prepareStatement("INSERT INTO image(name,path,tripId,eventId) VALUES(?,?,?,?)");
                        s.setString(1, itemName);
                        s.setString(2, root + finalimage);
                        s.setInt(3, tripId);
                        if (eventId >= 0) {
                            s.setInt(4, eventId);
                        } else {
                            s.setString(4, null);
                        }
                        try {
                            s.executeUpdate();
                        } catch (SQLException e) {
                        }
                    }
                    RequestDispatcher rd = request.getRequestDispatcher("accountpage.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                }
                try {
                    /* TODO output your page here. You may use following sample code. */
                    out.println("<html>");
                    out.println("<body>");
                    out.println("<table><tr><td>");
                    out.println("<img src='" + root + finalimage + "' width='40px' height='40px'/>");
                    out.println("</td></tr></table>");
                    out.println("</body>");
                    out.println("</html>");
                } finally {
                    out.close();
                }
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
